package com.atguigu.guli.service.edu.controller.admin;


import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.service.edu.entity.*;
import com.atguigu.guli.service.edu.entity.vo.CourseSearchObjVo;
import com.atguigu.guli.service.edu.feign.OssFileService;
import com.atguigu.guli.service.edu.feign.VodFileService;
import com.atguigu.guli.service.edu.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author liujun
 * @since 2021-01-20
 */
//@CrossOrigin
@RestController
@RequestMapping("/admin/edu/course")
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    SubjectService subjectService;
    @Autowired
    VideoService videoService;
    @Autowired
    VodFileService vodFileService;
    @Autowired
    OssFileService ossFileService;
    @Autowired
    CourseDescriptionService courseDescriptionService;
    //保存讲师
    @ApiOperation("保存课程信息")
    @PostMapping("/save-course-info")
    @Transactional(rollbackFor = Exception.class)
    public R save(@ApiParam(value = "课程信息", required = true) @RequestBody Course course) {
        course.setId(UUID.randomUUID().toString());
        //保存课程简介
        if(course.getDescription() !=null){
            final CourseDescription courseDescription = new CourseDescription();
            courseDescription.setCourseId(course.getId());
            courseDescription.setDescription(course.getDescription());
            courseDescriptionService.save(courseDescription);
        }
        final boolean res = courseService.save(course);
        if (res) {
            return R.ok().message("保存课程信息成功！").data("courseId",course.getId());
        }
        return R.error().message("保存课程信息失败！");
    }

    @ApiOperation("课程信息列表")
    @GetMapping("/list/{page}/{limit}")
    public R listPage(@ApiParam(value = "当前页码", required = true) @PathVariable Long page,
                      @ApiParam(value = "每页记录数", required = true) @PathVariable Long limit,
                      @ApiParam(value = "查询表单") CourseSearchObjVo searchObj) {
        Page<Course> pageParam = new Page<>(page, limit);
        IPage<Course> pageModel;
        final QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if (searchObj.getSubjectId() != null) {
            wrapper.eq("subject_id", searchObj.getSubjectId());
        }
        if (searchObj.getSubjectParentId() != null) {
            wrapper.eq("subject_parent_id", searchObj.getSubjectParentId());
        }
        if (searchObj.getTeacherId() != null) {
            wrapper.eq("teacher_id", searchObj.getTeacherId());
        }
        if (searchObj.getTitle() != null) {
            wrapper.like("title",searchObj.getTitle());
        }
        pageModel = courseService.page(pageParam, wrapper);
        List<Course> records = pageModel.getRecords();
        records.forEach(course -> {
            final String teacherName = teacherService.getById(course.getTeacherId()).getName();
            course.setTeacherName(teacherName);
            course.setSubjectParentTitle(subjectService.getById(course.getSubjectParentId()).getTitle());
            course.setSubjectTitle(subjectService.getById(course.getSubjectId()).getTitle());
        });
        long total = pageModel.getTotal();
        return R.ok().data("total", total).data("rows", records);
    }
    @ApiOperation("根据id查询课程信息")
    @GetMapping("/course-info/{id}")
    public R getById(@ApiParam(value = "课程信息id", required = true) @PathVariable String id) {
        final Course course = courseService.getById(id);
        //老师name 一级专业 二级专业
        course.setTeacherName(teacherService.getById(course.getTeacherId()).getName());
        course.setSubjectParentTitle(subjectService.getById(course.getSubjectParentId()).getTitle());
        course.setSubjectTitle(subjectService.getById(course.getSubjectId()).getTitle());
        final List<CourseDescription> courseDescriptions = courseDescriptionService.list(new QueryWrapper<CourseDescription>().eq("course_id", id));
        if(!CollectionUtils.isEmpty(courseDescriptions)){
            course.setDescription(courseDescriptions.get(0).getDescription());
        }
        if (course != null) {
            return R.ok().data("item", course).message("获取课程信息成功！");
        }
        return R.error().message("获取课程信息失败！");
    }

    @ApiOperation("更新课程信息")
    @PutMapping("/update-course-info")
    @Transactional(rollbackFor = Exception.class)
    public R update(@ApiParam(value = "课程信息", required = true) @RequestBody Course course) {
        final List<CourseDescription> courseDescriptions = courseDescriptionService.list(new QueryWrapper<CourseDescription>().eq("course_id", course.getId()));
        if(!CollectionUtils.isEmpty(courseDescriptions)){
            final CourseDescription courseDescription = courseDescriptions.get(0);
            final String oldDescription = courseDescription.getDescription();
            if(oldDescription != course.getDescription()){
                final CourseDescription updateCourseDes = new CourseDescription();
                updateCourseDes.setId(courseDescription.getId());
                updateCourseDes.setDescription(course.getDescription());
                courseDescriptionService.updateById(updateCourseDes);
            }
        }
        final boolean res = courseService.updateById(course);
        if (res) {
            return R.ok().message("更新课程信息成功！");
        }
        return R.error().message("更新课程信息失败！");
    }

    @ApiOperation("根据id删除课程信息")
    @DeleteMapping("/remove/{id}")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(@ApiParam(value = "id", required = true) @PathVariable String id) {
        //todo 删除课程中的所有视频
        //1、先删除阿里云上的所有视频
        final List<Video> videos = videoService.list(new QueryWrapper<Video>().eq("course_id", id));
        if(!CollectionUtils.isEmpty(videos)){
            final List<String> videoIds = videos.stream().map(Video::getVideoSourceId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(videoIds)){
                vodFileService.removeVideoByIdList(videoIds);
            }
        }
        //2、再删除数据库中视频记录
        videoService.remove(new QueryWrapper<Video>().eq("course_id", id));
        //todo 删除课程中的封面
        final Course course = courseService.getById(id);
        if(course!=null && course.getCover()!=null){
            ossFileService.removeFile(course.getCover());
        }
        //删除课程
        final boolean res = courseService.removeById(id);
        if (res) {
            return R.ok().message("删除课程信息成功！");
        }
        return R.error().message("删除课程信息失败！");
    }
    @ApiOperation("根据id发布课程")
    @PutMapping("publish-course/{id}")
    public R publishCourseById(
            @ApiParam(value = "课程ID", required = true)
            @PathVariable String id){
        final Course course = new Course();
        course.setId(id);
        course.setStatus(Course.COURSE_NORMAL);
        boolean result = courseService.updateById(course);
        if (result) {
            return R.ok().message("发布成功");
        } else {
            return R.error().message("数据不存在");
        }
    }
}

